package de.blitzcoder.cddatabase.gui.datatable;

import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author blitzcoder
 */
public class DataTable extends JTable {

    private TableRowSorter sorter;
    private DataTableRowFilter filter;

    private DataTableModel model;

    public DataTable(String[] columns) {
        this(columns, new int[columns.length]);
    }

    public DataTable(String[] columns, final int[] fixedColumnWidths) {

        super();

        model = new DataTableModel(columns);
        setModel(model);

        sorter = new TableRowSorter(getModel());

        filter = new DataTableRowFilter();
        sorter.setRowFilter(filter);

        setRowSorter(sorter);

        setDefaultRenderer(Object.class, new DataTableCellRenderer());

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                
            }
        });
        getModel().addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                for (int i=0;i<fixedColumnWidths.length;i++) {
                    if (fixedColumnWidths[i] > 0) {
                        System.out.println(i+" -> "+fixedColumnWidths[i]);
                        columnModel.getColumn(i).setMinWidth(fixedColumnWidths[i]);
                        columnModel.getColumn(i).setMaxWidth(fixedColumnWidths[i]);
                    }
                }
            }
        });

    }

    public void updateFilter(String txt) {
        filter.setFilter(txt);
        sorter.allRowsChanged();
    }

    @Override
    public DataTableModel getModel() {
        return (DataTableModel)model;
    }

}
